<?php
namespace app\controller;

use think\Db;
use think\Request;
use think\Response;
use think\Lang;

class Api extends Base
{

    public function test(){
        $str = [
            'en'=> 'jumping machine(跳楼机)',
        ];
        echo json_encode($str,JSON_UNESCAPED_UNICODE);
    }
    /**
     * 搜索歌词
     */
    public function search()
    {
        // 获取搜索关键词
        $start_time = time();
        $keyword = input('keyword', '','trim');
        
        // 如果关键词为空，返回错误
        if (empty($keyword)) {
            return $this->jsonReturn(202, Lang::get('keyword_required','keyword is required'));
        }
        $keyword = trim(str_replace(['歌词','歌詞','Lyrics','lyrics'],'', $keyword));

        // debug_dump($keyword);
        $search_history_id = db('search_history')->insertGetId([
            'keyword' => $keyword,
            'ip' => request()->ip(),
            'http_accept_language' => substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 200),
            'user_agent' => substr(request()->header('user-agent'), 0, 200),
            'language' => $this->_current_lang,
            'created_at' => date('Y-m-d H:i:s'),
        ]);
        // 先 在数据库查询是否有对应歌词
        $lyric_info = db('lyrics')->where(['title'=>$keyword,'language'=>$this->_current_lang])->find();
        if (!empty($lyric_info)) {
            // 更新搜索历史
            db('search_history')->where('id',$search_history_id)->update([
                'lyrics_id' => $lyric_info['id'],
            ]);

            $url = '';
            if ($lyric_info['status'] == 1) {
                $url = get_full_url_by_uri($this->_current_lang,'lyrics/'. rawurlencode($lyric_info['title_uri']));
            }
            $lyrics = [
                'title' => $lyric_info['title'],
                'artist' => $lyric_info['artist'],
                'album' => '',
                'lyrics' => $lyric_info['content'],
                'release_year' => '',
                'genre' => '',
                'url' => $url
            ];
            return $this->jsonReturn(200, Lang::get('search_success','search success'), $lyrics);
        }
        
        
        // 查询歌词
        $service = new \app\service\ApiService($this->_current_lang);
        $lyrics = $service->search($keyword);
        $process_time = time() - $start_time;
        
        $lyrics_id = 0;
        if (!empty($lyrics) && isset($lyrics['title']) && !empty($lyrics['title'])) {            
            $lyrics_info = db('lyrics')
            ->where(['title'=>$lyrics['title'],'language'=>$this->_current_lang])
            ->find();

            if (empty($lyrics_info)) {
                $lyrics_id = db('lyrics')->insertGetId([
                    'status' => 0,
                    'title_uri' => "{$lyrics['title_pinyin']}({$lyrics['title']})",
                    'title' => $lyrics['title'],
                    'artist' => $lyrics['artist'],
                    'title_pinyin' => $lyrics['title_pinyin'],
                    'artist_pinyin' => $lyrics['artist_pinyin'],
                    'language' => $this->_current_lang,
                    'content' => json_encode($lyrics['lyrics'],JSON_UNESCAPED_UNICODE),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s'),
                ]);
            }else{
                $lyrics_id = $lyrics_info['id'];
            }
        }
        // 更新搜索历史
        db('search_history')->where('id',$search_history_id)->update([
            'process_time' => $process_time,
            'lyrics_id' => $lyrics_id,
        ]);
        
        
        return $this->jsonReturn(200, Lang::get('search_success','search success'), $lyrics);
    }
    
  
    
    /**
     * 更新浏览量
     */
    public function updateViews(Request $request)
    {
        // 获取歌词ID
        $id = $request->param('id', 0);
        $type = $request->param('type', 'lyric');
        
        // 如果ID为空，返回错误
        if (empty($id)) {
            return $this->jsonReturn(400, '歌词ID不能为空');
        }
        
        try {
            // 查询歌词记录
            $lyric = Db::name('lyrics')
                ->where('id', $id)
                ->where('language', $this->_current_lang)
                ->find();
            
            if (empty($lyric)) {
                return $this->jsonReturn(404, '歌词记录未找到');
            }
            
            // 防止同一IP短时间内重复刷浏览量
            // $client_ip = request()->ip();
            // $cache_key = 'views_' . $lyric['id'] . '_' . md5($client_ip);
            // $last_view_time = cache($cache_key);
            
            // if ($last_view_time && (time() - $last_view_time) < 60) {
            //     // 1分钟内重复访问不增加浏览量
            //     return $this->jsonReturn(200, '浏览量统计成功', [
            //         'views' => $lyric['views'],
            //         'cached' => true
            //     ]);
            // }
            
            // 更新浏览量
            Db::name('lyrics')->where('id', $lyric['id'])->setInc('views');
            
            // 设置缓存，防止重复统计
            // cache($cache_key, time(), 60);
            
            // 获取更新后的浏览量
            $new_views = Db::name('lyrics')->where('id', $lyric['id'])->value('views');
            
            return $this->jsonReturn(200, '浏览量更新成功', [
                'views' => $new_views,
                'lyric_id' => $lyric['id'],
                'cached' => false
            ]);
            
        } catch (\Exception $e) {
            return $this->jsonReturn(500, '更新浏览量失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 更新下载量
     */
    public function updateDownloads(Request $request)
    {
        // 获取歌词ID
        $id = $request->param('id', 0);
        $type = $request->param('type', 'lyric');
        
        // 如果ID为空，返回错误
        if (empty($id)) {
            return $this->jsonReturn(400, '歌词ID不能为空');
        }
        
        try {
            // 查询歌词记录
            $lyric = Db::name('lyrics')
                ->where('id', $id)
                ->where('language', $this->_current_lang)
                ->find();
            
            if (empty($lyric)) {
                return $this->jsonReturn(404, '歌词记录未找到');
            }
            
            // 防止同一IP短时间内重复刷下载量
            $client_ip = request()->ip();
            $cache_key = 'downloads_' . $lyric['id'] . '_' . md5($client_ip);
            $last_download_time = cache($cache_key);
            
            if ($last_download_time && (time() - $last_download_time) < 30) {
                // 30秒内重复下载不增加下载量
                return $this->jsonReturn(200, '下载量统计成功', [
                    'downloads' => $lyric['downloads'] ?? 0,
                    'cached' => true
                ]);
            }
            
            // 更新下载量
            Db::name('lyrics')->where('id', $lyric['id'])->setInc('downloads');
            
            // 设置缓存，防止重复统计
            cache($cache_key, time(), 30);
            
            // 获取更新后的下载量
            $new_downloads = Db::name('lyrics')->where('id', $lyric['id'])->value('downloads');
            
            return $this->jsonReturn(200, '下载量更新成功', [
                'downloads' => $new_downloads,
                'lyric_id' => $lyric['id'],
                'cached' => false
            ]);
            
        } catch (\Exception $e) {
            return $this->jsonReturn(500, '更新下载量失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 更新打印量
     */
    public function updatePrints(Request $request)
    {
        // 获取歌词ID
        $id = $request->param('id', 0);
        $type = $request->param('type', 'lyric');
        
        // 如果ID为空，返回错误
        if (empty($id)) {
            return $this->jsonReturn(400, '歌词ID不能为空');
        }
        
        try {
            // 查询歌词记录
            $lyric = Db::name('lyrics')
                ->where('id', $id)
                ->where('language', $this->_current_lang)
                ->find();
            
            if (empty($lyric)) {
                return $this->jsonReturn(404, '歌词记录未找到');
            }
            
            // 防止同一IP短时间内重复刷打印量
            $client_ip = request()->ip();
            $cache_key = 'prints_' . $lyric['id'] . '_' . md5($client_ip);
            $last_print_time = cache($cache_key);
            
            if ($last_print_time && (time() - $last_print_time) < 30) {
                // 30秒内重复打印不增加打印量
                return $this->jsonReturn(200, '打印量统计成功', [
                    'prints' => $lyric['prints'] ?? 0,
                    'cached' => true
                ]);
            }
            
            // 更新打印量
            Db::name('lyrics')->where('id', $lyric['id'])->setInc('prints');
            
            // 设置缓存，防止重复统计
            cache($cache_key, time(), 30);
            
            // 获取更新后的打印量
            $new_prints = Db::name('lyrics')->where('id', $lyric['id'])->value('prints');
            
            return $this->jsonReturn(200, '打印量更新成功', [
                'prints' => $new_prints,
                'lyric_id' => $lyric['id'],
                'cached' => false
            ]);
            
        } catch (\Exception $e) {
            return $this->jsonReturn(500, '更新打印量失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 点赞歌词
     */
    public function like(Request $request)
    {
        // 获取歌词ID和类型
        $id = $request->param('id', 0);
        $type = $request->param('type', 'lyric');
        
        // 如果ID为空，返回错误
        if (empty($id)) {
            return $this->jsonReturn(400, '歌词ID不能为空');
        }
        
        try {
            // 查询歌词
            $lyric = Db::name('lyrics')
                ->where('id', $id)
                ->find();
            
            // 如果歌词不存在，返回错误
            if (empty($lyric)) {
                return $this->jsonReturn(404, '歌词记录未找到');
            }
            
            // 获取客户端IP，用于防止重复点赞
            $client_ip = request()->ip();
            $like_key = 'like_' . $id . '_' . md5($client_ip);
            $user_liked = cache($like_key);
            
            if ($user_liked) {
                // 如果已经点赞，则取消点赞
                if ($lyric['likes'] > 0) {
                    Db::name('lyrics')->where('id', $id)->setDec('likes');
                }
                cache($like_key, null); // 清除点赞缓存
                $new_user_liked = false;
                $action = '取消点赞';
            } else {
                // 如果未点赞，则添加点赞
                Db::name('lyrics')->where('id', $id)->setInc('likes');
                cache($like_key, time(), 86400 * 30); // 缓存30天
                $new_user_liked = true;
                $action = '点赞';
            }
            
            // 获取更新后的点赞数
            $new_likes = Db::name('lyrics')->where('id', $id)->value('likes');
            
            return $this->jsonReturn(200, $action . '成功', [
                'likes' => $new_likes,
                'user_liked' => $new_user_liked,
                'action' => $action
            ]);
            
        } catch (\Exception $e) {
            return $this->jsonReturn(500, '点赞操作失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 记录搜索关键词
     */
    private function recordSearchKeyword($keyword)
    {
        // 查询关键词是否存在
        $exists = Db::name('search_keyword')
            ->where('keyword', $keyword)
            ->find();
        
        if ($exists) {
            // 如果存在，更新搜索次数
            Db::name('search_keyword')
                ->where('id', $exists['id'])
                ->setInc('search_count');
        } else {
            // 如果不存在，添加新记录
            Db::name('search_keyword')
                ->insert([
                    'keyword' => $keyword,
                    'search_count' => 1,
                    'status' => 1,
                    'create_time' => time(),
                    'update_time' => time()
                ]);
        }
    }
    
    /**
     * 返回JSON格式数据
     */
    private function jsonReturn($code, $msg, $data = null)
    {
        $result = [
            'code' => $code,
            'msg' => $msg
        ];
        
        if ($data !== null) {
            $result['data'] = $data;
        }
        
        return Response::create($result, 'json');
    }
} 